<?php
namespace Crm\Table;

use Zend\Db\Sql\Select;
use Zend\Db\Sql\Where;

class MaterialCatalogTable extends AbstractTable
{

    protected $table = 'hy_material_catalog';

    protected $id = 'material_catalog_id';

    public function find($query = array())
    {
        $select = new Select(array(
            'o' => $this->getTable()
        ));
        $select->columns(array(
            'material_catalog_id',
            'material_catalog_name'
        ));
        
        if ($query['material_catalog_id']) {
            $select->where(array(
                'o.material_catalog_id' => $query['material_catalog_id']
            ));
        }
        
        $select->order('o.material_catalog_id DESC');
        
        return $this->fetchPaginate($select, $query);
    }

    public function findOne($id)
    {
        $rowset = $this->select(array(
            $this->getId() => $id
        ));
        $row = $rowset->current();
        return $row;
    }

    public function findAll()
    {
        $rowset = $this->select();
        $result = $rowset->toArray();
        return $result;
    }

    public function create($data)
    {
        return $this->insert($data);
    }

    public function updateById($data, $id)
    {
        return $this->update($data, array(
            $this->getId() => $id
        ));
    }

    public function remove()
    {}

    public function updateItem($id, $data)
    {
        if (empty($id)) {
            throw new \Exception("id field is invalid!");
        }
        $data = array(
            'resource_category_name' => $data['resource_category_name']
        );
        return $this->update($data, array(
            'material_catalog_id' => $id
        ));
    }

    public function deleteItem($id)
    {
        if (empty($id)) {
            throw new Exception("id field is invalid!");
        }
        return $this->delete(array(
            'material_catalog_id' => $id
        ));
    }

    public function addItem($data)
    {
        $data = array(
            'resource_category_name' => $data['resource_category_name']
        );
        
        $this->insert($data);
        $id = $this->lastInsertValue;
        
        return $id;
    }

    public function getItem($id)
    {
        if (empty($id)) {
            throw new Exception("id field is invalid!");
        }
        $sql = 'SELECT * FROM `hy_material_category` WHERE `material_catalog_id` =:material_catalog_id';
        $statement = $this->getAdapter()->query($sql);
        $results = $statement->execute(array(
            ':material_catalog_id' => $id
        ));
        $row = $results->current();
        return $row;
    }
}